class HomeController < ApplicationController
  @@waiting = -1

  def init_session
    session[:xn_sig_user] = params['xn_sig_user']
    session[:xn_sig_api_key] = params['xn_sig_api_key']
    session[:xn_sig_session_key] = params['xn_sig_session_key']
    session[:partner_session_id] = -1;
    session[:game_id] = -1
    session[:round_id] = -1
    session[:picture_id] = -1
    session[:user_id] = -1
    session[:tags] = Array.new
    session[:partner_count] = 0
    session[:status] = "waiting"
    session[:offlimit] = nil;
  end



  def index
    if params['xn_sig_user']!=nil
      init_session
      #user is an xml data
      user = get_xnuser_info(session[:xn_sig_user])
      @name = user.elements["name"].text
      @thumbnail = user.elements["headurl"].text
      @user = User.find_by_xid(session[:xn_sig_user])
      unless @user
        @user = User.new
        @user.xid = session[:xn_sig_user]
        @user.name = @name
        @user.thumbnail = @thumbnail
        @user.save
      end
      session[:user_id] = @user.id
    else
      puts "Can not access Xiaonei Data"
    end
  end

  #Request to start a game, or say, find a partner.
  def start
    #1st player comes. just wait
    if $waiting == -1||$waiting == session.session_id
      $waiting = session.session_id
    else
      puts "player2 comes."
      session[:partner_session_id] = $waiting
      get_partner_session
      @partner_session.data[:partner_session_id] = session.session_id
      @user = User.find_by_xid(@partner_session.data[:xn_sig_user])
      player1_id = @partner_session.data[:user_id]
      player2_id = session[:user_id]
      @game = Game.create_game_by_uid(player1_id, player2_id)
      @game.save
      set_both_attr_to_session(:game_id,@game.id)
      set_both_attr_to_session(:status,"gamebegin")
      generate_next_round
      @partner_session.save
      $waiting = -1;
    end

  end


  def gameover
    session[:status] = "gameover"
    session[:partner_session_id] = -1;
    session[:game_id] = -1
    session[:round_id] = -1
    session[:picture_id] = -1
    session[:tags] = Array.new
    session[:partner_count] = 0
    session[:offlimit] = nil;
    render :nothing => true;
  end

  def pass
    get_partner_session
    generate_next_round
    set_both_attr_to_session(:status,"pass")
    render :nothing =>true
  end

  def test
    render :partial =>'game/matched'
  end


  def period_call
    puts session[:status]
    get_partner_session
    #set partner info and next round.variable user,name,thumbnail holds the partner info
    if session[:status] == "roundbegin"
      session[:tags].clear
      session[:partner_count] = 0
      @picture = Picture.find(session[:picture_id])

    elsif session[:status] == "gamebegin"
      @partner = User.find_by_xid(@partner_session.data[:xn_sig_user])

    elsif session[:status] =="pass"
      
    elsif session[:status] == "playing"
      if params["tag"]!=nil&&params["tag"]!=""
        file = open('esplog.log', File::WRONLY | File::APPEND | File::CREAT)
        logger = Logger.new(file)
        logger.info("#{session[:xn_sig_user]} #{session[:picture_id]} #{params["tag"]} #{Time.now}")
        @tag = Tag.find_by_name(params["tag"])
        if @tag==nil
          @tag = Tag.new
          @tag.name = params["tag"]
          @tag.save
        end
        @tag.add_to_picture(session[:picture_id])
        session[:tags] << params["tag"]
        @partner_session.data[:partner_count] = session[:tags].length
        @game = Game.find(session[:game_id])
        @user = User.find(session[:user_id])
        if Tag.is_tag_in_bag(params["tag"], @partner_session.data[:tags])
          @game.score += 50;
          @user.score += 50;
          set_both_attr_to_session(:matched,params["tag"])
          generate_next_round
          set_both_attr_to_session(:status,"matched")
        else
          @game.score += 20;
          @user.score += 20;
          puts "not match..continue"
        end
        @game.save
        @user.save
        @partner_session.save
      end
    elsif session[:status] == "matched"
      
    end
  end

  def generate_next_round
    @game = Game.find(session[:game_id])
    @round = @game.get_next_round
    @picture = @round.picture
    @game.save
    @offlimit = @picture.get_offlimit_tag()
    set_both_attr_to_session(:offlimit,@offlimit)
    set_both_attr_to_session(:round_id,@round.id)
    set_both_attr_to_session(:picture_id,@picture.id)
  end

  def get_partner_session
    if session[:partner_session_id] != -1
      @partner_session = CGI::Session::ActiveRecordStore::Session.find_by_session_id(session[:partner_session_id]);
    else
      @partner_session = nil
    end
  end

  def set_both_attr_to_session(attr,value)
    session[attr] = value;
    if @partner_session == nil
      puts "partner sessions not exists."
    else
      @partner_session.data[attr] = value
    end
    
  end
  

end
